package com.eclink.iot.rfid;

import com.eclink.iot.base.DeviceBase;
import com.eclink.iot.utils.ByteUtils;
import java.net.Socket;


public class RFIDDeviceClient
  extends DeviceBase
{
  protected static final int API_COMMAND_INVENTORY = 34;
  protected static final int API_COMMAND_INVENTORY_MULTI = 39;
  protected static final int API_COMMAND_STOP = 40;
  private int api_inventory_errorcode = 255;
  
  private int api_inventory_multi_errorcode = 255;
  
  private int api_stop_errorcode = 255;
  
  public RFIDDeviceClient(Socket socket) {
    super(socket);
    
    this.TAG = "RFIDDeviceClient";

    // 停止掉原来的盘点操作
    stop_inventory();
  }

  
  public boolean inventory(int ant) {
    try {
      this.api_inventory_errorcode = 255;
      api_build_command(34, new byte[] { (byte)(ant >> 24 & 0xFF), (byte)(ant >> 16 & 0xFF), (byte)(ant >> 8 & 0xFF), (byte)(ant & 0xFF) });
      
      long time = System.currentTimeMillis();
      while (System.currentTimeMillis() - time < 5000L && this.api_inventory_errorcode == 255) {
        Thread.sleep(10L);
      }
      
      return (this.api_inventory_errorcode == 0);
    } catch (Exception ex) {
      return false;
    } 
  }
  
  public boolean inventory_multi(int ant) {
    try {
      this.api_inventory_multi_errorcode = 255;
      api_build_command(39, new byte[] { (byte)(ant >> 24 & 0xFF), (byte)(ant >> 16 & 0xFF), (byte)(ant >> 8 & 0xFF), (byte)(ant & 0xFF) });
      
      long time = System.currentTimeMillis();
      while (System.currentTimeMillis() - time < 5000L && this.api_inventory_multi_errorcode == 255) {
        Thread.sleep(10L);
      }
      return (this.api_inventory_multi_errorcode == 0);
    } catch (Exception ex) {
      return false;
    } 
  }
  
  public boolean stop_inventory() {
    try {
      this.api_stop_errorcode = 255;
      api_build_command(40, new byte[0]);
      
      long time = System.currentTimeMillis();
      while (System.currentTimeMillis() - time < 5000L && this.api_stop_errorcode == 255) {
        Thread.sleep(10L);
      }
      
      return (this.api_stop_errorcode == 0);
    } catch (Exception ex) {
      return false;
    } 
  }
  
  protected void command_receiving_notification(int type, byte[] buffer) {
    switch (type) {
      case 34:
        this.api_inventory_errorcode = 0;
        if (RFIDServer.rfid_tag_data_listener != null) {
          int lengthHigh = buffer[8] << 8 & 0xFF00;  // 长度的高位值
          int lengthLow =  buffer[7] & 0xFF;         // 长度的低位值
          int epc_length = (lengthHigh | lengthLow) / 8 * 2;
          int ant = buffer[5];
          String epc =  ByteUtils.toHexString(buffer, 9, epc_length, "");
          RFIDServer.rfid_tag_data_listener.notice(this.uuid, ant, epc);
        } 
        break;
      
      case 39:
        this.api_inventory_multi_errorcode = buffer[5];
        break;
      
      case 40:
        this.api_stop_errorcode = buffer[5];
        break;
    } 
  }
}

